package com.xxc.hs.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import com.xxc.hs.bean.SourceRecord;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

public class SourceDao {
    private static SourceDao instance;
    private SourceDbHelper dbHelper;
    private SQLiteDatabase database;
    private Context context;

    private SourceDao(Context context) {
        this.context = context;
        dbHelper = new SourceDbHelper(context);
    }

    public static synchronized SourceDao getInstance(Context context) {
        if (instance == null) {
            instance = new SourceDao(context.getApplicationContext());
        }
        return instance;
    }

    // 插入溯源记录
    public void insertRecord(SourceRecord record, InsertCallback callback) {
        new InsertTask(callback).execute(record);
    }

    // 根据批次号查询记录
    public LiveData<List<SourceRecord>> getRecordsByBatch(String batch) {
        MutableLiveData<List<SourceRecord>> liveData = new MutableLiveData<>();
        new GetRecordsTask(batch, records -> liveData.postValue(records)).execute();
        return liveData;
    }

    // 根据日期查询记录
    public LiveData<List<SourceRecord>> getRecordsByDate(String date) {
        MutableLiveData<List<SourceRecord>> liveData = new MutableLiveData<>();
        new GetRecordsByDateTask(date, records -> liveData.postValue(records)).execute();
        return liveData;
    }

    // 插入任务
    private class InsertTask extends AsyncTask<SourceRecord, Void, Long> {
        private InsertCallback callback;

        public InsertTask(InsertCallback callback) {
            this.callback = callback;
        }

        @Override
        protected Long doInBackground(SourceRecord... records) {
            database = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(SourceDbHelper.COLUMN_PRODUCT_NAME, records[0].getProductName());
            values.put(SourceDbHelper.COLUMN_PRODUCT_SPEC, records[0].getProductSpec());
            values.put(SourceDbHelper.COLUMN_PRODUCT_BATCH, records[0].getProductBatch());
            values.put(SourceDbHelper.COLUMN_FARMING_DATE, records[0].getFarmingDate());
            values.put(SourceDbHelper.COLUMN_FISHING_DATE, records[0].getFishingDate());
            values.put(SourceDbHelper.COLUMN_PROCESSING_DATE, records[0].getProcessingDate());
            values.put(SourceDbHelper.COLUMN_TRANSPORTATION_DATE, records[0].getTransportationDate());
            values.put(SourceDbHelper.COLUMN_SOURCE_INFO, records[0].getSourceInfo());
            values.put(SourceDbHelper.COLUMN_INPUT_TIME, records[0].getInputTime());

            long newRowId = database.insert(SourceDbHelper.TABLE_NAME, null, values);
            database.close();
            return newRowId;
        }

        @Override
        protected void onPostExecute(Long aLong) {
            if (callback != null) {
                callback.onInsertComplete(aLong);
            }
        }
    }

    @SuppressLint("Range")
    // 查询任务
    private class GetRecordsTask extends AsyncTask<Void, Void, List<SourceRecord>> {
        private String batch;
        private RecordsCallback callback;

        public GetRecordsTask(String batch, RecordsCallback callback) {
            this.batch = batch;
            this.callback = callback;
        }

        @Override
        protected List<SourceRecord> doInBackground(Void... voids) {
            database = dbHelper.getReadableDatabase();
            String[] projection = {
                    SourceDbHelper.COLUMN_ID,
                    SourceDbHelper.COLUMN_PRODUCT_NAME,
                    SourceDbHelper.COLUMN_PRODUCT_SPEC,
                    SourceDbHelper.COLUMN_PRODUCT_BATCH,
                    SourceDbHelper.COLUMN_FARMING_DATE,
                    SourceDbHelper.COLUMN_FISHING_DATE,
                    SourceDbHelper.COLUMN_PROCESSING_DATE,
                    SourceDbHelper.COLUMN_TRANSPORTATION_DATE,
                    SourceDbHelper.COLUMN_SOURCE_INFO,
                    SourceDbHelper.COLUMN_INPUT_TIME
            };
            String selection = SourceDbHelper.COLUMN_PRODUCT_BATCH + " = ?";
            String[] selectionArgs = {batch};
            String sortOrder = SourceDbHelper.COLUMN_INPUT_TIME + " DESC";

            Cursor cursor = database.query(
                    SourceDbHelper.TABLE_NAME,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
            );

            List<SourceRecord> records = new ArrayList<>();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(SourceDbHelper.COLUMN_ID));
                String productName = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_NAME));
                String productSpec = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_SPEC));
                String productBatch = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_BATCH));
                String farmingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_FARMING_DATE));
                String fishingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_FISHING_DATE));
                String processingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PROCESSING_DATE));
                String transportationDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_TRANSPORTATION_DATE));
                String sourceInfo = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_SOURCE_INFO));
                String inputTime = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_INPUT_TIME));

                records.add(new SourceRecord(id, productName, productSpec, productBatch,
                        farmingDate, fishingDate, processingDate, transportationDate, sourceInfo, inputTime));
            }
            cursor.close();
            database.close();
            return records;
        }

        @Override
        protected void onPostExecute(List<SourceRecord> records) {
            if (callback != null) {
                callback.onRecordsLoaded(records);
            }
        }
    }

    @SuppressLint("Range")
    // 按日期查询任务
    private class GetRecordsByDateTask extends AsyncTask<Void, Void, List<SourceRecord>> {
        private String date;
        private RecordsCallback callback;

        public GetRecordsByDateTask(String date, RecordsCallback callback) {
            this.date = date;
            this.callback = callback;
        }

        @Override
        protected List<SourceRecord> doInBackground(Void... voids) {
            database = dbHelper.getReadableDatabase();
            String[] projection = {
                    SourceDbHelper.COLUMN_ID,
                    SourceDbHelper.COLUMN_PRODUCT_NAME,
                    SourceDbHelper.COLUMN_PRODUCT_SPEC,
                    SourceDbHelper.COLUMN_PRODUCT_BATCH,
                    SourceDbHelper.COLUMN_FARMING_DATE,
                    SourceDbHelper.COLUMN_FISHING_DATE,
                    SourceDbHelper.COLUMN_PROCESSING_DATE,
                    SourceDbHelper.COLUMN_TRANSPORTATION_DATE,
                    SourceDbHelper.COLUMN_SOURCE_INFO,
                    SourceDbHelper.COLUMN_INPUT_TIME
            };
            String selection = "(" + SourceDbHelper.COLUMN_FARMING_DATE + " = ? OR " +
                    SourceDbHelper.COLUMN_FISHING_DATE + " = ? OR " +
                    SourceDbHelper.COLUMN_PROCESSING_DATE + " = ? OR " +
                    SourceDbHelper.COLUMN_TRANSPORTATION_DATE + " = ?)";
            String[] selectionArgs = {date, date, date, date};
            String sortOrder = SourceDbHelper.COLUMN_INPUT_TIME + " DESC";

            Cursor cursor = database.query(
                    SourceDbHelper.TABLE_NAME,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
            );

            List<SourceRecord> records = new ArrayList<>();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(SourceDbHelper.COLUMN_ID));
                String productName = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_NAME));
                String productSpec = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_SPEC));
                String productBatch = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PRODUCT_BATCH));
                String farmingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_FARMING_DATE));
                String fishingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_FISHING_DATE));
                String processingDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_PROCESSING_DATE));
                String transportationDate = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_TRANSPORTATION_DATE));
                String sourceInfo = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_SOURCE_INFO));
                String inputTime = cursor.getString(cursor.getColumnIndex(SourceDbHelper.COLUMN_INPUT_TIME));

                records.add(new SourceRecord(id, productName, productSpec, productBatch,
                        farmingDate, fishingDate, processingDate, transportationDate, sourceInfo, inputTime));
            }
            cursor.close();
            database.close();
            return records;
        }

        @Override
        protected void onPostExecute(List<SourceRecord> records) {
            if (callback != null) {
                callback.onRecordsLoaded(records);
            }
        }
    }

    // 回调接口
    public interface InsertCallback {
        void onInsertComplete(long rowId);
    }

    public interface RecordsCallback {
        void onRecordsLoaded(List<SourceRecord> records);
    }
}